package com.ling.module1sbbyyds.service.news;

import com.ling.sbbyyds.entity.news.Message;
import com.ling.sbbyyds.entity.users.User;
import com.ling.sbbyyds.mapper.news.MessageMapper;
import com.ling.sbbyyds.mapper.user.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 聊天
 */
@Service
@Slf4j
public class MessageService {

    @Autowired(required = false)
    MessageMapper messageMapper;

    @Autowired(required = false)
    UserMapper userMapper;

    /**
     * 获取用户所有好友未读的信息
     * @param  userId   获取未读消息的用户
     * @return
     */
    public List<List<Message>> getAllUserUnreadNews(Long userId){
        try {
            //存放信息列表
            List<List<Message>> messageList = new ArrayList<>(20);
            //获取有发送未读消息的好友列表
            ArrayList<Long> haveUnreadUserList = messageMapper.getUserUnreadUserList(userId);
            //遍历获取每个用户的消息
            for (Long friendId : haveUnreadUserList) {
                //每个好友的未读消息列表
                ArrayList<Message> unreadNews = messageMapper.getUserUnreadNews(userId, friendId);
                if(!ObjectUtils.isEmpty(unreadNews)){
                    //获取发送的用户头像
                    User user = userMapper.selectByPrimaryKey(friendId);
                    for (Message unreadNew : unreadNews) {
                        unreadNew.setUserName(user.getUserName());
                        unreadNew.setHeadImage(user.getAvatar());
                    }
                    messageList.add(unreadNews);
                }
            }
            return messageList;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

}
